﻿using Microsoft.Extensions.DependencyInjection;
using SBlogCore.Common.DispatchProxyIn;
using SBlogCore.EventBus.CrossProcessEventBus.Model;
using System.Reflection;

namespace SBlogCore.EventBus.CrossProcessEventBus.Proxy
{
    /// <summary>
    /// 事件总线代理
    /// </summary>
    public class EventBusDispatchProxy : GlobalDispatchProxy
    {
        protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
        {
            if (targetMethod==null)
            {
                throw new Exception("方法不存在");
            }
            //获取当前实例
            var type=targetMethod.DeclaringType?.GetInterfaces();
            if (type==null)
                throw new Exception("必须继承接口IEventBusDispatchProxy");
            var eventHandlers = ServiceProvider?.GetService<IEnumerable<IEventBus>>();
            if (eventHandlers==null)
                throw new Exception("必须为IEventBus注入实现类");
            var eventHandler = eventHandlers.FirstOrDefault(f => f is EventBusHandler);
            if (eventHandlers == null)
                throw new Exception("未找到EventBusHandler实例");
            EventMember member = new EventMember(targetMethod);
            return eventHandler?.Publish(member.EventName, args);
            ////如果包含接口ICrossEventBusDispatchProxy，说明是跨进程的
            //if (type.Contains(typeof(ICrossEventBusDispatchProxy)))
            //{

            //}
            ////这里准备写进程内的EventBus 
            //else
            //{

            //}
            //return null;
        }
    }
}
